package com.asset.dispoal.file.casedispose.service.command;

import com.asset.dispoal.business.bsCase.domain.db.entity.BsCase;
import com.asset.dispoal.business.bsCase.domain.db.entity.CaseStateRecord;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.commom.menus.AgreementCaseSateMenu;
import com.asset.dispoal.file.casedispose.dto.FileCaseExecutionRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.Date;

@Component
public class FileCaseExecutionCommand implements BaseCommand<FileCaseExecutionRequest, Result> {
    @Autowired
    FileCaseDisposeSaveFileCommand fileCaseDisposeSaveCommand;

    @Autowired
    BsCaseMapper caseMapper;

    @Autowired
    BaseIdeable<String> ideable;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(FileCaseExecutionRequest request) {
        String userId = GlobalHeaderThreadLocal.get().getUserId();
        Date currentDate = DateTimeUtil.currentDate();
        String caseState = AgreementCaseSateMenu.EXECUTION.getLabel();
        if (request.getExecutionFile() != null) {
            fileCaseDisposeSaveCommand.execute(request.getId(), request.getExecutionFile(), caseState, "executionFile");
        }
        BsCase bsCase = new BsCase();
        bsCase.setId(request.getId());
        bsCase.setCaseState(caseState);
        bsCase.setOperateUser(userId);
        bsCase.setOperateTime(currentDate);
        bsCase.setExecutionTime(request.getExecutionTime());
        bsCase.setExecutionNumber(request.getExecutionNumber());
        caseMapper.execution(bsCase);
        CaseStateRecord caseStateRecord = new CaseStateRecord();
        caseStateRecord.setId(ideable.generateId());
        caseStateRecord.setOldState(AgreementCaseSateMenu.JUDGMENT.getLabel());
        caseStateRecord.setNewState(caseState);
        caseStateRecord.setCaseId(request.getId());
        caseStateRecord.setCreateUser(userId);
        caseMapper.insertStateRecord(caseStateRecord);
        return Result.ok();
    }
}